import React, { useContext, useState } from "react";
import Backdrop from "../../Backdrop/Backdrop";
import Meal from "../../../Meals/Meal/Meal";
import classes from "./CartDetail.module.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faTrash } from "@fortawesome/free-solid-svg-icons";
import CartContext from "../../../../store/cart";
import Confirm from "../../Confirm/Confirm";

function CartDetail() {
  const cxt = useContext(CartContext);

  // 设置state控制确认框的显示
  const [showConfirm, setShowConfirm] = useState(false);

  // 添加函数显示确认窗口
  const showConfirmHandler = () => {
    setShowConfirm(true);
  };

  const cancelHandler = (e) => {
    e.stopPropagation();
    setShowConfirm(false);
  };

  const okHandler = () => {
    // 清空购物车
    // cxt.clearCart();
    cxt.cartDispatch({type: 'CLS'})
  };

  return (
    <Backdrop>
      {showConfirm && <Confirm
          onCancel={cancelHandler}
          onOk={okHandler}
          confirmText={"确认清空购物车吗？"}
        />
      }
      <div className={classes.CartDetail} onClick={(e) => e.stopPropagation()}>
        <header>
          <h2>餐品详情</h2>
          <div className={classes.Clear} onClick={showConfirmHandler}>
            <FontAwesomeIcon icon={faTrash} />
            <span style={{ marginLeft: "10rem" }}>清空购物车</span>
          </div>
        </header>

        {/* 餐品 */}
        <div className={classes.MealList}>
          {cxt.items.map((item) => (
            <Meal noDesc key={item.id} meal={item} />
          ))}
        </div>
      </div>
    </Backdrop>
  );
}

export default CartDetail;
